package cn.cscb.mms.common.utils;

import cn.cscb.mms.common.exception.AuthenticationExcetpion;
import cn.cscb.mms.common.exception.BaseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import javax.crypto.SecretKey;
import java.util.Map;

@Slf4j
@Component
public class JwtUtil {

    @Value("${jwt.key}")
    private String key;
    public String createJwt(Object payload){
        //1.对秘钥做BASE64编码
        String base64 = Base64Utils.encodeToString(key.getBytes());
        //2.生成秘钥对象,会根据base64长度自动选择相应的 HMAC 算法
        SecretKey secretKey = Keys.hmacShaKeyFor(base64.getBytes());
        //3.利用JJWT生成Token
        try {
            String json = new ObjectMapper().writeValueAsString(payload);
            return Jwts.builder().subject(json).signWith(secretKey).compact();
        } catch (JsonProcessingException e) {
            log.error("JSON解析失败",e);
            throw new AuthenticationExcetpion("JSON解析失败");
        }
    }

    public Map checkJwt(String jwt){
        String base64 = Base64Utils.encodeToString(key.getBytes());
        //2.生成秘钥对象,会根据base64长度自动选择相应的 HMAC 算法
        SecretKey secretKey = Keys.hmacShaKeyFor(base64.getBytes());
        //3.验证Token
        JwtParser parser = Jwts.parser().verifyWith(secretKey).build();
        //解析JWT
        Jwt<?, ?> obj = parser.parse(jwt);
        Claims payload = (Claims)obj.getPayload();
        try {
            return new ObjectMapper().readValue(payload.getSubject(), Map.class);
        } catch (JsonProcessingException e) {
            log.error("无效Payload",e);
            throw new AuthenticationExcetpion("无效Payload");
        }
    }
}
